<?php

/**
 * @Author: king
 * @Date:   2019-01-24 15:50:29
 * @Last Modified by:   king
 * @Last Modified time: 2019-01-26 11:55:18
 */
namespace App\Http\Controllers\Api\v2;

use App\Models\Api\Orders;
use App\Models\Api\Recode;

use App\Http\Controllers\Controller;
use DB;

/**
 * 活动相关接口
 * Class IdentifyLove
 * @package App\Http\Controllers\Api\v2
 */
class CheckActiveController extends Controller
{
    /**
     * 暂时不用后台处理，支付成功后回调
     * @method GET
     * @param int page 分页页码
     * @return \think\response\Json
     * @throws \app\common\lib\exception\ApiException
     */
    public function index($map=[])
    {
        $uid=$map['uid'] ?? 0;
        $gid=$map['gid'] ?? 0;
        $rids=$map['rids'] ?? 0;  //多个档案
        $pay_unlock_time = date('Y',$map['pay_unlock_time']) ?? 0;

        $test = [
            'uid'=>$uid,
            'gid'=>$gid,
            'rids'=>$rids,
            'pay_unlock_time'=>$pay_unlock_time
        ];

        \Log::info('WxPay_Notify_Arr:'. json_encode($test,true));

        //检查是否在活动时间内购买的年运
        $active = checktime();
        if ($active && in_array($gid,[24,25,26,27]))
        {
            //给多个档案赠送运势
            foreach ($rids as $r)
            {
                //获取用户已购买的日运订单
                $orders1 = (new Orders())->fortune_orders(['uid' => $uid, 'rid' => $r, 'type' => 1]);
                //获取用户已购买的月运订单
                $orders2 = (new Orders())->fortune_orders(['uid' => $uid, 'rid' => $r, 'type' => 2]);

                $orders = array_merge($orders1,$orders2);

                //订单解锁时间
                $unlock_time = [];
                //订单解锁时间范围
                $order_time1 = [];
                $order_time2 = [];
                $unlock_time_range1 = [];
                $unlock_time_range2 = [];

                if ($orders && !empty($orders))
                {
                    //获取档案解锁的时间信息
                    foreach ($orders as $k => $v)
                    {
                        //获取日运的解锁时间范围
                        if ($v['type'] == 1)
                        {
                            $extend = json_decode($v['extend'], true);
                            if (isset($extend['expire_time']) && $extend['expire_time'])
                            {
                                $v['expire_time'] = $extend['expire_time'];
                            }
                            $start_time = date('Y-n-j', $v['time']);
                            $end_time = date('Y-n-j', strtotime($v['expire_time'], $v['time'])- 86400);

                            $unlock_time['start_time'] = $start_time;
                            $unlock_time['end_time'] = $end_time;

                            $order_time1[] = prDates(['start' => $unlock_time['start_time'], 'end' => $unlock_time['end_time'], 'type' => 1]);

                        } //获取月运的解锁时间范围
                        elseif ($v['type'] == 2)
                        {
                            $extend = json_decode($v['extend'], true);
                            if (isset($extend['expire_time']) && $extend['expire_time'])
                            {
                                $v['expire_time'] = $extend['expire_time'];
                            }
                            $start_time = date('Y-n', $v['time']);
                            $end_time = date('Y-n', strtotime($v['expire_time'], $v['time'])- 86400 *30);

                            $unlock_time['start_time'] = $start_time;
                            $unlock_time['end_time'] = $end_time;

                            $order_time2[] = prDates(['start' => $unlock_time['start_time'], 'end' => $unlock_time['end_time'], 'type' => 2]);

                        }
                    }

                    //将日运解锁的时间范围重组
                    foreach ($order_time1 as $k => $v)
                    {
                        foreach ($v as $vv)
                        {
                            $unlock_time_range1[] = $vv;
                        }
                    }

                    //将月运解锁的时间范围重组
                    foreach ($order_time2 as $k => $v)
                    {
                        foreach ($v as $vv)
                        {
                            $unlock_time_range2[] = $vv;
                        }
                    }
                    //将日运解锁时间范围从大到小排序，获取最后解锁的时间
                    if ($unlock_time_range1)
                    {
                        rsort($unlock_time_range1);
                        $unlock_time_range1 = explode('-',array_slice($unlock_time_range1,0,1)[0]) ;
                    }
                    //将月运解锁时间范围从大到小排序，获取最后解锁的时间
                    if ($unlock_time_range2)
                    {
                        rsort($unlock_time_range2);
                        $unlock_time_range2 = explode('-',array_slice($unlock_time_range2,0,1)[0]) ;
                    }

                    //重组赠送的时间
                    $extend1 = json_encode(['award_time'=>strtotime(implode('-',[$unlock_time_range1[0],$unlock_time_range1[1],$unlock_time_range1[2]]))],true);
                    $extend2 = json_encode(['award_time'=>strtotime(implode('-',[$unlock_time_range2[0],$unlock_time_range2[1]]))],true);

                }else{
                    //重组赠送的时间
                    $extend1 = json_encode(['award_time'=>strtotime($pay_unlock_time.'-1-1')],true);
                    $extend2 = json_encode(['award_time'=>strtotime($pay_unlock_time.'-1')],true);
                }

                //赠送日运
                $arr1=[
                    'uid'=>$uid,
                    'rid'=>$r,
                    'extend'=>$extend1,
                    'create_time'=>time()
                ];
                //赠送月运
                $arr2=[
                    'uid'=>$uid,
                    'rid'=>$r,
                    'extend'=>$extend2,
                    'create_time'=>time()
                ];
                //购买一年运势享受8折优惠，再送每日运势一个月，每月运势一个月。
                //三年运势享受8折优惠，再送每日运势三个月，每月运势三个月。
                //五年运势享受8折优惠，再送每日运势五个月，每月运势五个月。
                //十年运势享受8折优惠，再送一年每日运势与每月运势。
                switch ($gid) {
                    case 24:
                        $arr1['aid'] = 3;
                        $arr2['aid'] = 20;
                        break;
                    case 25:
                        $arr1['aid'] = 4;
                        $arr2['aid'] = 21;
                        break;
                    case 26:
                        $arr1['aid'] = 5;
                        $arr2['aid'] = 22;
                        break;
                    case 27:
                        $arr1['aid'] = 6;
                        $arr2['aid'] = 23;
                        break;
                }
                //赠送日运
                DB::table('award_user')->insert($arr1);
                Cache::forget($uid.'_award_fortune_1');
                //赠送月运,并加入计算
                $mid = DB::table('award_user')->insertGetId($arr2);
                Cache::forget($uid.'_award_fortune_2');
                $this->push_fortune($mid);
            }
        }

        return ;
    }


    /**月运赠送重新计算
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function push_fortune($mid=0){

        $data = DB::table('award_user')
            ->from('award_user as au')
            ->select('au.create_time','au.extend','au.status','u.username','u.nickname','u.sex','u.uen','u.id as uid','u.tel','g.expire_time','au.rid')
            ->join('goods as g','au.aid','=','g.id','LEFT')
            ->join('user as u','au.uid','=','u.id','LEFT')
            ->where('au.id',$mid)
            ->first();
//        $recode_name = Db::table('wechat.app_recode')
//            ->alias('r')
//            ->field('r.*')
//            ->where('id',$data['rid'])
//            ->find();
        $recode_name = (new Recode())->getRecode(['id'=>$data['rid']]);

        $award_time = json_decode($data['extend'],true)['award_time'];
        $end_time = strtotime($data['expire_time'],$award_time)- 86400*30;
        $datas['type'] = "month";
        $datas['ftype'] = 3;
        $datas['aid'] =$mid;
        $datas['recode'][] = $recode_name;

        $start_time = prDates([
            'start' => date('Y-m',$award_time),
            'end' => date('Y-m',$end_time),
            'type' => 2,
        ]);
        $datas['start_time'] = $start_time;
        //加入队列
        if (!empty($datas)) {
            $fortune_job_setting = config('fortune_job');

            $delay = $fortune_job_setting['delay'];
            if (getVip($datas['recode'][0]['uid']) >= 1)
            {
                $delay = 0;
            }
            queuePush($fortune_job_setting['task'], $datas, $fortune_job_setting['queue'], $delay);
        }

        return ;
    }

}
